package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"godemo/models"
	"strconv"
)

type VoteController struct{}

func (v VoteController) AddVote(c *gin.Context) {
	playerIdStr := c.PostForm("playerId")
	playerId, _ := strconv.Atoi(playerIdStr)
	userId := c.PostForm("userId")
	session := sessions.Default(c)
	loginInfoSession := session.Get("login:" + userId)
	fmt.Println("redis取出值：", loginInfoSession)
	if loginInfoSession == nil {
		ReturnError(c, 0, "登录失效，请重新登录")
		return
	}

	var loginInfo UserLoginVO
	loginInfoStr, ok := loginInfoSession.(string)
	if !ok {
		fmt.Println(ok)
	}

	err := json.Unmarshal([]byte(loginInfoStr), &loginInfo)
	if err != nil {
		fmt.Println("json格式转换异常：", err)
		return
	}
	fmt.Println("转好对象值：", loginInfo)
	id, err := models.AddVote(loginInfo.Id, playerId)
	if err != nil {
		fmt.Println(err)
	}

	err = models.UpdateScore(playerId)
	if err != nil {
		fmt.Println("更新分数失败：", err)
		return
	}
	ReturnSuccess(c, 200, "成功", id, 1)
}
